package com.engine.api.gdyjs.util;

import com.engine.api.gdyjs.entity.AssetsInfo;
import com.engine.api.gdyjs.entity.MonthlyZcrkStat;
import com.engine.api.gdyjs.entity.AnnualZcrkStat;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class AssetsMoneyNumStatUtils {
    private static final DateTimeFormatter DATE_FORMATTER =
            DateTimeFormatter.ofPattern("yyyy-MM-dd");

    // 缓存日期解析结果，避免重复解析
    private static final Map<String, LocalDate> DATE_CACHE = new ConcurrentHashMap<>();

    /**
     * 获取完整的统计报告（年度+月度）
     * @param list 资产列表
     * @return 包含年度和月度统计的Map
     */
    public static Map<String, Object> getCurrentPeriodDetailReport(List<AssetsInfo> list) {
        Map<String, Object> report = new HashMap<>();

        // 年度统计
        report.put("annualStats", getAnnualStatistics(list));

        // 月度统计
        report.put("monthlyStats", getMonthlyStatistics(list));

        return report;
    }

    /**
     * 年度统计：追溯历史8年数据（数量+金额）
     * @param list 资产列表
     * @return 按年度分组的统计结果列表
     */
    public static List<AnnualZcrkStat> getAnnualStatistics(List<AssetsInfo> list) {
        // 空值检查
        if (list == null || list.isEmpty()) {
            return createEmptyAnnualStats();
        }

        // 过滤掉已处置的数据
        List<AssetsInfo> filteredList = list.stream()
                .filter(asset -> !"已处置".equals(asset.getZcsyzt()))
                .filter(AssetsMoneyNumStatUtils::isValidAsset)
                .collect(Collectors.toList());

        int currentYear = LocalDate.now().getYear();
        // 计算起始年度（当前年度往前推7年）
        int startYear = currentYear - 7;

        // 按年度分组统计数量和金额
        Map<Integer, AnnualZcrkStat> resultMap = filteredList.stream()
                .filter(asset -> {
                    try {
                        String qyrq = asset.getQyrq(); // 启用日期
                        if (qyrq == null || qyrq.trim().isEmpty()) {
                            return false;
                        }
                        LocalDate date = parseDate(qyrq);
                        int assetYear = date.getYear();
                        return assetYear >= startYear && assetYear <= currentYear;
                    } catch (Exception e) {
                        return false;
                    }
                })
                .collect(Collectors.groupingBy(
                        asset -> {
                            try {
                                return parseDate(asset.getQyrq()).getYear();
                            } catch (Exception e) {
                                return -1;
                            }
                        },
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                assets -> {
                                    if (assets.isEmpty()) {
                                        return null;
                                    }

                                    long count = assets.size();
                                    BigDecimal totalAmount = assets.stream()
                                            .map(asset -> {
                                                BigDecimal amount = asset.getZcdqcbwy();
                                                return amount != null ? amount : BigDecimal.ZERO;
                                            })
                                            .reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(10000), BigDecimal.ROUND_HALF_UP);

                                    try {
                                        assets =assets.stream().filter(asset -> asset.getQyrq() != null).collect(Collectors.toList());
                                        AssetsInfo firstAsset = assets.get(0);
                                        if (firstAsset != null && firstAsset.getQyrq() != null) {
                                            int year = parseDate(firstAsset.getQyrq()).getYear();
                                            return new AnnualZcrkStat(year, count, totalAmount);
                                        }
                                    } catch (Exception e) {
                                        // 解析失败，使用默认值
                                    }
                                    return new AnnualZcrkStat(-1, count, totalAmount);
                                }
                        )
                ));

        // 移除无效的分组
        resultMap.remove(-1);
        resultMap.values().removeIf(Objects::isNull);

        // 确保所有年度都有数据（即使为0）
        List<AnnualZcrkStat> result = new ArrayList<>();
        for (int year = startYear; year <= currentYear; year++) {
            if (resultMap.containsKey(year)) {
                AnnualZcrkStat stat = resultMap.get(year);
                if (stat != null) {
                    result.add(stat);
                } else {
                    result.add(new AnnualZcrkStat(year, 0, BigDecimal.ZERO));
                }
            } else {
                result.add(new AnnualZcrkStat(year, 0, BigDecimal.ZERO));
            }
        }

        // 按年份排序
        return result.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(AnnualZcrkStat::getYear))
                .collect(Collectors.toList());
    }

    /**
     * 月度统计：追溯历史12个月数据（数量+金额）
     * @param list 资产列表
     * @return 按月度分组的统计结果列表
     */
    public static List<MonthlyZcrkStat> getMonthlyStatistics(List<AssetsInfo> list) {
        // 空值检查
        if (list == null || list.isEmpty()) {
            return createEmptyMonthlyStats();
        }

        // 过滤掉已处置的数据
        List<AssetsInfo> filteredList = list.stream()
                .filter(asset -> !"已处置".equals(asset.getZcsyzt()))
                .filter(AssetsMoneyNumStatUtils::isValidAsset)
                .collect(Collectors.toList());

        YearMonth currentYearMonth = YearMonth.now();
        // 计算起始年月（当前年月往前推11个月）
        YearMonth startYM = currentYearMonth.minusMonths(11);

        // 按月度分组统计数量和金额
        Map<String, MonthlyZcrkStat> resultMap = filteredList.stream()
                .filter(asset -> {
                    try {
                        String qyrq = asset.getQyrq(); // 启用日期
                        if (qyrq == null || qyrq.trim().isEmpty()) {
                            return false;
                        }
                        LocalDate date = parseDate(qyrq);
                        YearMonth assetYM = YearMonth.from(date);
                        return !assetYM.isBefore(startYM) && !assetYM.isAfter(currentYearMonth);
                    } catch (Exception e) {
                        return false;
                    }
                })
                .collect(Collectors.groupingBy(
                        asset -> {
                            try {
                                return YearMonth.from(parseDate(asset.getQyrq())).toString();
                            } catch (Exception e) {
                                return "invalid";
                            }
                        },
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                assets -> {
                                    if (assets.isEmpty()) {
                                        return null;
                                    }

                                    long count = assets.size();
                                    BigDecimal totalAmount = assets.stream()
                                            .map(asset -> {
                                                BigDecimal amount = asset.getZcdqcbwy();
                                                return amount != null ? amount : BigDecimal.ZERO;
                                            })
                                            .reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(10000), BigDecimal.ROUND_HALF_UP);

                                    try {
                                        assets =assets.stream().filter(asset -> asset.getQyrq() != null).collect(Collectors.toList());
                                        AssetsInfo firstAsset = assets.get(0);
                                        if (firstAsset != null && firstAsset.getQyrq() != null) {
                                            String yearMonth = YearMonth.from(parseDate(firstAsset.getQyrq())).toString();
                                            return new MonthlyZcrkStat(yearMonth, count, totalAmount);
                                        }
                                    } catch (Exception e) {
                                        // 解析失败，使用默认值
                                    }
                                    return new MonthlyZcrkStat("invalid", count, totalAmount);
                                }
                        )
                ));

        // 移除无效的分组
        resultMap.remove("invalid");
        resultMap.values().removeIf(Objects::isNull);

        // 确保所有月份都有数据（即使为0）
        List<MonthlyZcrkStat> result = new ArrayList<>();
        YearMonth tempYM = startYM;
        while (!tempYM.isAfter(currentYearMonth)) {
            String yearMonthStr = tempYM.toString();
            if (resultMap.containsKey(yearMonthStr)) {
                MonthlyZcrkStat stat = resultMap.get(yearMonthStr);
                if (stat != null) {
                    result.add(stat);
                } else {
                    result.add(new MonthlyZcrkStat(yearMonthStr, 0, BigDecimal.ZERO));
                }
            } else {
                result.add(new MonthlyZcrkStat(yearMonthStr, 0, BigDecimal.ZERO));
            }
            tempYM = tempYM.plusMonths(1);
        }

        // 按年月排序
        return result.stream()
                .filter(Objects::nonNull)
                .sorted(Comparator.comparing(MonthlyZcrkStat::getYearMonth))
                .collect(Collectors.toList());
    }

    /**
     * 获取指定年度的统计汇总
     */
    public static Map<String, Object> getAnnualSummary(List<AssetsInfo> list, int year) {
        Map<String, Object> summary = new HashMap<>();

        List<AnnualZcrkStat> annualStats = getAnnualStatistics(list);
        AnnualZcrkStat targetYearStat = annualStats.stream()
                .filter(stat -> stat.getYear() == year)
                .findFirst()
                .orElse(new AnnualZcrkStat(year, 0, BigDecimal.ZERO));

        summary.put("year", year);
        summary.put("count", targetYearStat.getCount());
        summary.put("amount", targetYearStat.getAmount());
        summary.put("annualStats", annualStats);

        return summary;
    }

    /**
     * 获取指定年月的统计汇总
     */
    public static Map<String, Object> getMonthlySummary(List<AssetsInfo> list, String yearMonth) {
        Map<String, Object> summary = new HashMap<>();

        List<MonthlyZcrkStat> monthlyStats = getMonthlyStatistics(list);
        MonthlyZcrkStat targetMonthStat = monthlyStats.stream()
                .filter(stat -> stat.getYearMonth().equals(yearMonth))
                .findFirst()
                .orElse(new MonthlyZcrkStat(yearMonth, 0, BigDecimal.ZERO));

        summary.put("yearMonth", yearMonth);
        summary.put("count", targetMonthStat.getCount());
        summary.put("amount", targetMonthStat.getAmount());
        summary.put("monthlyStats", monthlyStats);

        return summary;
    }

    /**
     * 验证资产数据的有效性
     */
    private static boolean isValidAsset(AssetsInfo asset) {
        if (asset == null) {
            return false;
        }

        // 检查必要字段 - 现在检查启用日期
        if (asset.getQyrq() == null || asset.getQyrq().trim().isEmpty()) {
            return false;
        }

        // 验证日期格式
        try {
            parseDate(asset.getQyrq());
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * 带缓存的日期解析方法
     */
    private static LocalDate parseDate(String dateStr) {
        if (dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        }

        return DATE_CACHE.computeIfAbsent(dateStr, key -> {
            try {
                return LocalDate.parse(key, DATE_FORMATTER);
            } catch (DateTimeParseException e) {
                throw new RuntimeException("日期格式错误: " + key, e);
            }
        });
    }

    /**
     * 创建空的年度统计
     */
    private static List<AnnualZcrkStat> createEmptyAnnualStats() {
        int currentYear = LocalDate.now().getYear();
        int startYear = currentYear - 7;
        List<AnnualZcrkStat> annualStats = new ArrayList<>();

        for (int year = startYear; year <= currentYear; year++) {
            annualStats.add(new AnnualZcrkStat(year, 0, BigDecimal.ZERO));
        }

        return annualStats;
    }

    /**
     * 创建空的月度统计
     */
    private static List<MonthlyZcrkStat> createEmptyMonthlyStats() {
        YearMonth currentYearMonth = YearMonth.now();
        YearMonth startYM = currentYearMonth.minusMonths(11);
        List<MonthlyZcrkStat> monthlyStats = new ArrayList<>();

        YearMonth tempYM = startYM;
        while (!tempYM.isAfter(currentYearMonth)) {
            monthlyStats.add(new MonthlyZcrkStat(tempYM.toString(), 0, BigDecimal.ZERO));
            tempYM = tempYM.plusMonths(1);
        }

        return monthlyStats;
    }

    /**
     * 清空日期缓存
     */
    public static void clearDateCache() {
        DATE_CACHE.clear();
    }

    /**
     * 获取缓存大小（用于监控）
     */
    public static int getCacheSize() {
        return DATE_CACHE.size();
    }
}